Add @FocusState and .focused - #49
Merged
Merged
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Adds
@FocusStateand.focused(_:)/.focused(_:equals:), giving Swift two-way control of keyboard focus.Shape
@FocusStatestores its value in the same persistedStateBox@Stateuses, so it survives re-evaluation and participates in updates. Its$-projection is a distinctFocusState.Bindingtype, so only focus state can be bound to a field's focus.init()is available forBooland optional values, matching SwiftUI..focused(_:)(Bool) and.focused(_:equals:)(optionalHashable, to arbitrate between fields) emit afocusedmodifier carrying whether this field currently holds focus plus a bool callback.FocusRequesterto the field: aLaunchedEffectrequests focus when Swift says it should hold it and clears focus when it shouldn't, whileonFocusChangedreports the user's own focus moves back into the state.The ordering subtlety
When focus moves from field A to B, both fire — A's blur and B's focus, in no guaranteed order. A naive blur handler clearing the state would wipe out the focus B just claimed. So the blur path only surrenders focus if the state still names that field. Covered by a dedicated test (a stale blur from the first field must not clear the second's focus), and confirmed live on-device.
Verification
swift test— two new tests (Bool round-trip;equals:arbitration incl. the stale-blur case), 71 total passingEmailand the secondEditText(y 686–862) reportedfocused="true"— the correct field, not just anyEditTextand updated the label toName(the Email→Name handoff exercising the ordering guard)focus = nil) left zero focusedEditTexts and the label atnoneScope
Focus is wired into
TextField/SecureField(the same node type). Other controls accept the modifier but don't yet act on it.